<template>
  <div class="bottomControl">
    <audio :src="musicUrl" hidden ref="audioRef" autoplay @play="changeState(true)" @pause="changeState(false)" @ended="changeMusic('next')" @timeupdate="timeupdate"></audio>
    <!-- 左边 -->
    <div class="left">
      <div class="avatar" @click="$store.commit('changeMusicDetailCardState')">
        <img :src="musicDetail.al.picUrl" alt="" v-if="musicDetail.al" />
        <img src="@/assets/img/test.jpg" alt="" v-else />
      </div>
      <div class="musicInfo">
        <div class="musicName" v-if="musicDetail && musicDetail.name">
          {{ musicDetail.name }}
        </div>
        <div class="singer" v-if="musicDetail && musicDetail.name">
          {{ musicDetail.ar[0].name }}
        </div>
      </div>
      <div class="downloadContainer" v-if="musicDetail.name">
        <i class="iconfont icon-download" @click="downloadCurrentMusic"></i>
      </div>
    </div>
    <!-- 中间 -->
    <div class="center">
      <div class="buttons">
        <span><i class="iconfont icon-xunhuan"></i></span>
        <span @click="musicList.length  ? changeMusic('pre') : ''"><i class="iconfont icon-shangyishou"></i></span>
        <span @click="musicList.length ? changePlayState() : ''">
          <i class="iconfont icon-icon_play" v-if="!$store.state.isPlay"></i>
          <i class="iconfont icon-zantingtingzhi" v-else></i>
        </span>
        <span @click="musicList.length   ? changeMusic('next') : ''"><i class="iconfont icon-xiayishou"></i></span>
        <span><i class="iconfont icon-xihuan" :class="isUserLikeCurrentMusic ? 'like' : ''" @click="musicList.length != 0 ? likeIt() : ''"></i></span>
      </div>
      <!-- 进度条 -->
      <div class="progressBar">
        <span class="currentTime">{{ currentTime | handleMusicTime }}</span>
        <!-- :value 是单向的  要实现双向要v-model -->
        <el-slider class="progressSlider" v-model="timeProgress" :show-tooltip="false" @change="changeProgress" :disabled="musicList.length == 0"></el-slider>
        <span class="totalTime">{{ duration }}</span>
      </div>
    </div>
    <!-- 右边 -->
    <div class="right">
      <div class="volumeControl">
        <i class="iconfont icon-yinliang" @click="changeMutedState"></i>
        <el-slider class="volumeSlider" v-model="volume" @input="changeVolume" :show-tooltip="false"></el-slider>
      </div>
      <div class="playList" @click="openDrawer">
        <i class="iconfont icon-bofangliebiao"></i>
      </div>
      <!-- 备案信息 -->
      <el-tooltip class="item" effect="dark" placement="left" :enterable="false">
        <div v-html="recondInfo" slot="content"></div>
        <el-link type="info" href="https://beian.miit.gov.cn/" target="_blank" class="recondInfo">粤ICP备2021068014号-2</el-link>
      </el-tooltip>
    </div>
    <!-- 抽屉 -->
    <el-drawer :visible.sync="drawer" :with-header="false" width="300">
      <div class="drawerHeader">总{{ musicList.length }}首</div>
      <el-table :data="musicList" stripe style="width: 100%" :show-header="false" @row-dblclick="clickRow" highlight-current-row lazy>
        <el-table-column prop="name" width="150px"> </el-table-column>
        <el-table-column prop="ar[0].name" width="80px"> </el-table-column>
        <el-table-column prop="dt" width="70px"> </el-table-column>
      </el-table>
    </el-drawer>
  </div>
</template>

<script>
import { reqUserLikeList, reqSongsUrl } from '@/network/api'
import { handleMusicTime, returnSecond } from '@/plugins/utils'
import { onMounted, inject, ref, reactive, watch, toRefs } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
let lastSecond = 0
// 总时长的秒数
let durationNum = 0
// 保存当前音量
let volumeSave = 0
// 当前音乐类型，用于下载
let musicType = ''

export default {
  name: 'bottomControl',

  setup() {
    const data = reactive({
      musicDetail: {},
      musicUrl: '',
      musicList: [],
      likeMusicList: [],
      drawer: false,
      duration: '00:00',
      currentTime: 0,
      timeProgress: 0,
      volume: 30,
      isMuted: false
    })
    const store = useStore()
    const audioRef = ref(null)
    const $message = inject('$message')

    const getLikeMusicList = async () => {
      const res = await reqUserLikeList(store.state.userInfo.id)
      if (res.code !== 200) {
        $message.error(res.msg)
        return
      }
      data.likeMusicList = res.ids
      store.commit('updateLikeMusicList', res.ids)
    }

    const downloadCurrentMusic = () => {
      let url = musicUrl.match(/\http.*?\.net/)[0]
      let serve = url.match(/http:\/(\S*).music/)[1]
      const arr = ['/m7', '/701', '/m8', '/m801']
      if (arr.indexOf(serve) === -1) {
        $message.error('匹配不到对应的代理')
        return
      }
      let params = musicUrl.slice(url.length)
      const downloadMusicInfo = {
        name: musicDetail.name + '-' + musicDetail.ar[0].name + '.' + musicType,
        url: serve.params
      }
      store.commit('updateDownloadMusicInfo', downloadMusicInfo)
    }
    const timeUpdate = () => {
      let time = audioRef.value.currentTime
      store.commit('updateCurrentTime', time)
      time = Math.floor(time)
      if (time !== lastSecond) {
        lastSecond = time
        data.currentTime = time
        data.timeProgress = Math.floor((time / durationNum) * 100)
      }
    }
    const openDrawer = () => {
      data.drawer = !data.drawer
      data.hasDrawerOpend = true
      handleDrawerListDOM(data.currentMusicIndex)
    }
    const getIsUserLikeCurrentMusic = () => {
      const id = store.state.musicId
      data.isUserLikeCurrentMusic = data.likeMusicList.find(v => v.id === id)
    }
    const likeIt = async () => {
      if (!store.state.userInfo) {
        $message.error('请先登陆')
        return
      }
      data.isUserLikeCurrentMusic = !data.isUserLikeCurrentMusic
      const res = await reqAddLikeCurrentMusic(store.state.musicId, data.isUserLikeCurrentMusic)
      if (res.code === 200) {
        getLikeMusicList()
        console.log('likecao操作成功')
      } else {
        console.log('likecao操作失败')
      }
    }
    const getMusicDetail = async id => {
      store.commit('updateMusicLoadState', true)
      let res = await reqSongsUrl(id)
      if (res.data[0].url == null) {
        $message.error('该歌曲暂无版权')
        changeMusic('next')
        return
      }
      data.musicUrl = res.data[0].url
      musicType = res.data[0].type.toLowerCase()
      store.commit('updateMusicLoadState', false)
    }

    const handleDrawerListDOM = (current, last) => {
      const tableDom = document.querySelector('.bottomControl tbody')
      const tableRows = tableDom.querySelectorAll('.el-table__row')
      if (tableRows[current]) {
        tableRows[current].children[0].querySelector('.cell').classList.add('currentRow')
        tableRows[current].children[1].querySelector('.cell').classList.add('currentRow')
      }
      if (last && last != -1) {
        tableRows[last].children[0].querySelector('.cell').classList.remove('currentRow')
        tableRows[last].children[1].querySelector('.cell').classList.remove('currentRow')
      }
    }
    const changeState = state => {
      store.commit('changePlayState', state)
    }
    const getMusicDetailFromMusicList = () => {
      data.musicList.forEach((v, i) => {
        if (v.id === store.state.musicId) {
          data.currentMusicIndex = i
          store.commit('updateCurrentIndex', i)
          data.musicDetail = v
          data.duration = v.dt
        }
      })
    }
    const changePlayState = () => {
      store.state.isPlay ? playMusic() : pasueMusic()
    }
    const playMusic = () => {
      audioRef.value.play()
    }
    const pauseMusic = () => {
      console.log(audioRef)
      audioRef.value.pause()
    }
    const changeProgress = e => {
      data.currentTime = Math.floor((e / 100) * durationNum)
      audioRef.value.currentTime = data.currentTime
    }
    const changeVolume = e => {
      audioRef.value.volume = e / 100
      if (data.isMuted && e > 0) {
        data.isMuted = false
      } else if (e == 0 && data.isMuted == false) {
        data.isMuted = true
      }
    }
    const changeMutedState = () => {
      if (data.isMuted) {
        data.volume = volumeSave
      } else {
        volumeSave = data.volume
        data.volume = 0
      }
      data.isMuted = !data.isMuted
    }
    const changeMusic = (type, id) => {
      let i = 0
      if (type === 'click') {
        store.commit('updateMusicId', id)
        return
      } else if (type === 'pre') {
        i = (i - 1 + data.currentMusicIndex) % data.currentMusicIndex
      } else if (type === 'next') {
        i = (i + 1) % data.currentMusicIndex
      }
      store.commit('updateMusicId', data.musicList[i].id)
    }
    const clickRow = row => {
      changeMusic('click', row.id)
    }
    onMounted(() => {
      if (store.state.userInfo) {
        getLikeMusicList()
      }
    })
    watch(
      () => {
        return store.state.musicId
      },
      id => {
        pauseMusic()
        data.musicList = store.state.musicList
        getMusicDetailFromMusicList()
        getMusicDetail(id)
        durationNum = returnSecond(data.duration)
        getIsUserLikeCurrentMusic()
      }
    )
    watch(
      () => store.state.currntIndex,
      (current, last) => {
        if (data.hasDrawerOpend) {
          handleDrawerListDOM(current, last)
        }
      }
    )
    watch(
      () => store.state.isPlay,
      current => {
        if (current) {
          playMusic()
        } else {
          pauseMusic()
        }
      }
    )
    return {
      ...toRefs(data),
      store,
      audioRef,
      changeState,
      changeMusic,
      changePlayState
    }
  }
}
</script>

<style scoped>
.bottomControl {
  /* background-color: pink; */
  border-top: 1px solid #ddd;
  width: 100%;
  height: 55px;
  position: fixed;
  bottom: 0;
  left: 0;
  display: flex;
  justify-content: space-between;
  padding: 6px 10px;
  z-index: 10000;
  background-color: #fff;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 5px;
  overflow: hidden;
  margin-right: 10px;
  cursor: pointer;
}

.avatar img {
  width: 100%;
}

.left {
  display: flex;
  align-items: center;
  width: 123px;
}

.musicInfo {
  color: rgb(37, 37, 37);
  font-size: 12px;
  width: 70px;
}

.musicName {
  margin-bottom: 4px;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.singer {
  transform: scale(0.9);
  margin-left: -3px;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.center {
  margin-top: 5px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.buttons {
  display: flex;
  align-items: center;
  height: 13px;
}

.buttons i {
  font-size: 20px;
  color: #313131;
}

.buttons span:nth-child(3) i {
  font-size: 25px;
}

.center .icon-xunhuan {
  font-size: 17px;
}
.center .icon-xihuan {
  font-size: 15px;
}

.right {
  display: flex;
  align-items: center;
  position: relative;
}

.volumeControl {
  display: flex;
  align-items: center;
  margin-right: 15px;
}

.icon-yinliang {
  font-size: 18px;
  margin-right: 7px;
}

.volumeSlider {
  width: 55px;
}

.icon-bofangliebiao {
  font-size: 18px;
  margin-right: 10px;
}

.progressSlider {
  width: 300px;
}

.buttons span {
  display: inline-block;
  width: 50px;
  box-sizing: border-box;
  text-align: center;
}

.icon-zantingtingzhi {
  font-size: 35px !important;
}

.drawerHeader {
  font-size: 12px;
  transform: scale(0.9);
  color: #aaa;
  padding: 15px 0;
}

.progressBar {
  display: flex;
  align-items: center;
}

.currentTime,
.totalTime {
  font-size: 12px;
  transform: scale(0.85);
  color: #aaa;
  margin: 0 5px;
  width: 30px;
  text-align: center;
}

.progressBar {
  height: 10px;
  margin-top: 12px;
  overflow: hidden;
}

.like {
  color: #ec4141 !important;
}

.downloadContainer {
  height: 100%;
  position: relative;
}

.downloadContainer i {
  position: absolute;
  bottom: 5px;
}

.recondInfo {
  position: absolute;
  font-size: 12px;
  transform: scale(0.8);
  width: 140px;
  right: -5px;
  bottom: -5px;
}
</style>